using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

namespace Steup
{
    public class FileSystem
    {
        public static readonly FileSystem Instance = new FileSystem();

        public void LoadFile(string url, System.Action<string, object> onComplete, object userdata = null)
        {
            SetupSystem.Instance.StartCoroutine(DoLoadFile(url, onComplete, userdata));
        }

        public void LoadFile(string url, System.Action<byte[], object> onComplete, object userdata = null)
        {
            SetupSystem.Instance.StartCoroutine(DoLoadFile(url, onComplete, userdata));
        }

        private IEnumerator DoLoadFile(string url, System.Action<string, object> onComplete, object userdata)
        {
            Debug.Log($"Load: {url}");
            var request = UnityWebRequest.Get(url);
            yield return request.SendWebRequest();
            if (request.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.LogErrorFormat("[LoadFile] URL:{0} Error:{1}", url, request.error);
            }
            else
            {
                DownloadHandler handler = request.downloadHandler;
                if (string.IsNullOrEmpty(handler.text) && handler.data.Length == 0)
                {
                    Debug.LogErrorFormat("[LoadFile] URL:{0} Error:{1}", url, request.error);
                }
                onComplete.Invoke(handler.text, userdata);
            }
        }

        private IEnumerator DoLoadFile(string url, System.Action<byte[], object> onComplete, object userdata)
        {
            Debug.Log($"Load: {url}");
            var request = UnityWebRequest.Get(url);
            yield return request.SendWebRequest();
            if (request.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.LogErrorFormat("[LoadFile] URL:{0} Error:{1}", url, request.error);
            }
            else
            {
                DownloadHandler handler = request.downloadHandler;
                if (string.IsNullOrEmpty(handler.text) && handler.data.Length == 0)
                {
                    Debug.LogErrorFormat("[LoadFile] URL:{0} Error:{1}", url, request.error);
                }
                onComplete.Invoke(handler.data, userdata);
            }
        }
    }
}